/**
 * 将list转为tree格式的数据
 * 实现方式： 建索引法
 * 核心：把父节点相同的子节点归类，并根据它们父节点的id建立索引
 * {
    "0":[
        {id: 1, name: 'child1', parentId: 0},
        {id: 2, name: 'child2', parentId: 0},
        {id: 3, name: 'child3', parentId: 0}
    ],
    "1":[
        "0": {id: 5, name: "child1_2", parentId: 1}
        "1": {id: 4, name: "child1_1", parentId: 1}
    ],
    "2":[
        {id: 2, name: 'child2', parentId: 0}
    ],
    "3":[
        {id: 7, name: 'child3_1', parentId: 3}
    ],
    "null":[
        {id: 0, name: 'root', parentId: null}
  
 * */ 

export function transfrom (list) {
    console.log(list, "list")
    const group = {};
    
    list.forEach(item => {
        const parentId = item.parentId;
        
        if (!Object.prototype.hasOwnProperty.call(group, parentId)) {
            group[parentId] = [];
        }
        group[parentId].push(item);
    })

    list.forEach(item => {
        let id = item.id;
        if (Object.prototype.hasOwnProperty.call(group, id)) {
            item.children = group;
        }
    })

    return group['null']
}


// export function listToTree (list) {
//     let info = list.reduce((map, node) =>(map[node.id] = node, map), {})
//     console.log(info, "info");
//     return list.filter(node => {
//         if (node.parentId == 'root') {
//             console.log(info[node.parentId].children)
//             info[node.parentId].children.push(node)
//         }
//         return node.parentId;
//     })
// }


export function listToTree(oldArr){
    oldArr.forEach(element => {
      let parentId = element.parentid;
      if(parentId !== 'root'){
        oldArr.forEach(ele => {
          if(ele.id == parentId){ //当内层循环的ID== 外层循环的parendId时，（说明有children），需要往该内层id里建个children并push对应的数组；
            if(!ele.children){
              ele.children = [];
            }
            ele.children.push(element);
          }
        });
      }
    });
    console.log(oldArr) //此时的数组是在原基础上补充了children;
    oldArr = oldArr.filter(ele => ele.parentid === 'root'); //这一步是过滤，按树展开，将多余的数组剔除；
    console.log(oldArr)
    return oldArr;
}